#!/usr/bin/env node
const { program } = require('commander');
const inquirer = require('inquirer');
const chalk = require('chalk').default;
const prompt = inquirer.createPromptModule();
const fetchSvg = require('./script/fetch.js')

const { exec } = require('child_process');

const fs = require('fs'); // 引入 fs 模块
const path = require('path'); // 引入 path 模块

function getDirectories(srcPath) {
  return fs.readdirSync(srcPath) // 读取目录内容
    .map(name => path.join(srcPath, name)) // 构建完整路径
    .filter(source => fs.statSync(source).isDirectory()); // 过滤目录
}

const isConfirm = async (message) => {
  const answers = await prompt([
    {
      type: 'confirm',
      name: 'confirm',
      message: `[${message}] ? `,
      default: true,
    },
  ]);
  if (!answers.confirm) {
    console.log('❌ 退出');
    process.exit(0); // 明确退出进程
  }
}


const projectPath = path.join(__dirname, `projects`);
const directories = getDirectories(projectPath); // 获取一级目录
projects = directories.map(dir => dir.split('/').pop())

const CREATE = { name: 'New project', value: 'create', short: 'n' }
const FETCH = { name: 'Fetch sample', value: 'fetch', short: 'f' }
const UPDATE = { name: 'Update urls', value: 'update', short: 'u' }
const COMPILE = { name: 'Compile project', value: 'compile', short: 'c' }
const PROXY = { name: 'Proxy compile', value: 'proxy', short: 'p' }
const QUIT = { name: 'Quit menu', value: 'quit', short: 'q' }

const listQuestions = [{
  type: 'list',
  name: 'operate',
  message: 'SELECT OPERATION: ',
  choices: [FETCH, CREATE, UPDATE, COMPILE, PROXY, QUIT],
  default: FETCH
}];

const createQuestions = [{
  type: 'input',
  name: 'projectName',
  message: 'Please enter a project name',
  default: ''
}];

const fetchQuestions = [{
  type: 'input',
  name: 'sampleName',
  message: 'Enter sample name: ',
  default: 'demo'
}, {
  type: 'input',
  name: 'sampleUrl',
  message: 'Enter target url: ',
  default: 'https://mp.weixin.qq.com/s/BB3aFtOw0tpUNe-5_WRsDQ'
}, {
  type: 'list',
  name: 'sampleDownloadFolder',
  message: 'Which folder do you want to download: ',
  choices: ['projects', 'samples',]
}];

const currDirList = '\n' + projects.map((project, idx) => `[${idx}]${project}`).join('\n')

const generateQuestions = [{
  type: 'input',
  name: 'generateName',
  message: 'Eenter a project name to update urls.json file',
  default: currDirList
}];

const proxyQuestions = [{
  type: 'input',
  name: 'proxyName',
  message: 'Input name or index to compile',
  default: currDirList
}];

const compileQuestions = [{
  type: 'input',
  name: 'compileName',
  message: 'Input name or index to compile',
  default: currDirList
}, {
  type: 'checkbox',
  name: 'compileOptions',
  message: 'What skills do you have?',
  choices: [
    { name: 'UploadImages', checked: false },
  ]
}];

const commandOptions = {
  ['create']: () => prompt(createQuestions),
  ['update']: () => prompt(generateQuestions),
  ['fetch']: () => prompt(fetchQuestions),
  ['compile']: () => prompt(compileQuestions),
  ['proxy']: () => prompt(proxyQuestions),
  ['quit']: () => { process.exit(0); },
}

program
  .version('1.0.0', '-V, --version', '显示版本号')
  .configureHelp({
    helpWidth: 100,
    optionTerm: (option) => option.flags,
    subcommandTerm: (cmd) => cmd.name()
  })
  .configureOutput({
    outputError: (err, write) => write(err.replace('error: ', ''))
  })
  .addHelpText('after', '\n示例:\n  $ svg-cli create')
  .command('help [command]')
  .description('显示命令帮助')
  .option('-v, --verbose', '输出详细日志');

program.command('start')
  .description('项目工具')
  .action(async () => {
    try {
      const { operate } = await prompt(listQuestions)
      const option = await commandOptions[operate]()
      const { projectName, sampleName, sampleUrl, sampleDownloadFolder,
        generateName, compileName, compileOptions, proxyName } = option

      if (projectName) {
        require('./script/utils/create-project')(projectName);
        console.log(`✅ 项目 ${projectName} 创建成功`);
        exec(`open ./projects/${projectName}`, () => { });
        return
      }

      if (sampleName && sampleDownloadFolder === 'projects' && projects.includes(sampleName)) {
        console.error(`❌ Name: [${sampleName}] exists`);
        process.exit(0);
      }
      if (sampleName && sampleUrl) {
        const success = await fetchSvg({ name: sampleName, url: sampleUrl, folder: sampleDownloadFolder })
        if (!success) { console.error(`❌ ERRor Url is null`); }
        const isInSample = sampleDownloadFolder === 'projects'
        return
      }

      if (generateName) {
        const updateUrls = require('./script/utils/update-urls.js');
        let generateProject = projects[generateName] || generateName
        generateProject = projects.includes(generateProject) ? generateProject : 'dev'
        await isConfirm(generateProject)
        await updateUrls(generateProject)
        console.log(`✅ 项目 ${generateProject}/urls.json updated`);
        return
      }

      // 服务直接编译用命令
      if (compileName) {
        let compileProject = projects[compileName] || compileName
        compileProject = projects.includes(compileProject) ? compileProject : 'dev'
        await isConfirm(compileProject)

        await require('./script/compile')(compileProject, compileOptions);
        console.log(`✅ 项目${compileProject} compiled`);

        exec(`open ./projects/${compileProject}`, () => { });
        return
      }

      // 执行本地shell 调用服务器编译命令, 返回编译代码
      if (proxyName) {
        let proxyProject = projects[proxyName] || proxyName
        proxyProject = projects.includes(proxyProject) ? proxyProject : 'dev'
        await isConfirm(proxyProject)
        console.log(`[${projects[proxyName]}] 开始编译...`);

        const command = `bash ./script/utils/proxy-compile.sh ${proxyProject}`

        exec(command, (error, stdout, stderr) => {
          if (error) {
            console.error(`执行脚本时出错: ${error.message}`);
            return;
          }
          if (stderr) {
            console.error(`脚本错误: ${stderr}`);
            return;
          }
          console.log(`脚本输出: ${stdout}`);
        });
        return // 必须加return 语句,不然会提取退出,无法执行shell
      }

      process.exit(0); // 明确退出进程
    } catch (error) {
      console.error(`❌ 创建失败: ${error.message}`);
      process.exit(1);
    }

  });

// 用于给远程shell调用的命令, 实现服务器代理编译功能
program.command('compile')
  .description('编译项目')
  .option('-n, --name <type>', '项目名称')
  .action(async (options) => {
    try {
      const compileProject = options.name
      const compileOptions = ['UploadImages']
      await require('./script/compile')(compileProject, compileOptions);
    } catch (error) {
      console.error(`❌ 编译失败: ${error.message}`);
      process.exit(1);
    }
  })

program.parse(process.argv); // 确保这行在文件末尾


/*
const questions = [{
    type: 'password',
    name: 'password',
    message: 'Enter a password',
    mask: '*'
}];
*/
